﻿<%@ Page Language="C#" AutoEventWireup="true" EnableSessionState="True" %>

<%@ Register TagPrefix="Hi" Namespace="Hidistro.UI.SaleSystem.Tags" Assembly="Hidistro.UI.SaleSystem.Tags" %>
<%@ Register TagPrefix="Hi" Namespace="Hidistro.UI.Common.Controls" Assembly="Hidistro.UI.Common.Controls" %>
<%@ Register TagPrefix="wnxd" Namespace="wnxd.Web" Assembly="wnxd.Web" %>
<%@ Import Namespace="Hidistro.Entities.Sales" %>
<%@ Import Namespace="Hidistro.SaleSystem.Shopping" %>
<%@ Import Namespace="Hidistro.Entities.Orders" %>
<%@ Import Namespace="Hidistro.Messages" %>
<%@ Import Namespace="Hidistro.Membership.Context" %>
<%@ Import Namespace="Hidistro.Core" %>
<%@ Import Namespace="Hidistro.Membership.Core" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="Hidistro.Entities" %>
<%@ Import Namespace="wnxd.javascript" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="Hidistro.SaleSystem.Catalog" %>
<%@ Import Namespace="Hidistro.Entities.Promotions" %>
<%@ Import Namespace="Hidistro.SqlDal.Sales" %>
<html>
<head>
    <script type="text/javascript" src="http://res.juseshop.com/Utility/jquery-1.6.4.min.js"></script>
    <script type="text/javascript" src="http://res.juseshop.com/Utility/jquery.artDialog.js"></script>
    <link type="text/css" rel="stylesheet" href="http://res.juseshop.com/Utility/skins/opera.css" />
</head>
<body>
    <wnxd:Web runat="server"></wnxd:Web>
</body>
</html>
<script runat="server">

    private string verifyCodeKey = "VerifyCode";
    private bool CheckVerifyCode(string verifyCode)
    {
        if (HttpContext.Current.Request.Cookies[this.verifyCodeKey] == null)
        {
            return false;
        }
        return (string.Compare(HiCryptographer.Decrypt(HttpContext.Current.Request.Cookies[this.verifyCodeKey].Value), verifyCode, true, CultureInfo.InvariantCulture) == 0);
    }

    private void ErrorReturn(Web wnxd_web, string msg)
    {
        wnxd_web.AddScript("art.dialog({ title: \"提示\", content: \"" + msg + "\", cancel: true, fixed: true, close: function(){ location.href = \"" + this.Request.UrlReferrer.OriginalString + "#hot\" } });");
    }
    private bool IsMobilePhone(string input)
    {
        Regex regex = new Regex("^1[23456798][0-9]{9}$");
        return regex.IsMatch(input);
    }
    protected void Post()
    {
        Web wnxd_web = Web.FindFirst();
        try
        {
            //if (this.Request["verifycode"] != null)
            //{
            //    string verifycode = (verifycode = this.Request["verifycode"]) == "" ? "未填" : verifycode.Trim();
            //    if (!this.CheckVerifyCode(verifycode))
            //    {
            //        ErrorReturn(wnxd_web, "验证码错误");
            //        return;

            //    }
            //}
            int region;
            if (!int.TryParse(this.Request["regionSelectorValue"], out region) || region == 0)
            {
                ErrorReturn(wnxd_web, "请选择收货地址");
                return;
            }
            string pattern = @"[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5_a-zA-Z0-9]*";
            Regex regex = new Regex(pattern);
            if (!(!string.IsNullOrEmpty(this.Request["shr"]) && regex.IsMatch(this.Request["shr"].Trim())))
            {
                ErrorReturn(wnxd_web, "请输入正确的收货人姓名");
                return;
            }
            if ((this.Request["shr"].Length < 2) || (this.Request["shr"].Length > 20))
            {
                ErrorReturn(wnxd_web, "收货人姓名长度应在2-20个字符之间");
                return;
            }
            if (string.IsNullOrEmpty(this.Request["shdz"]))
            {
                ErrorReturn(wnxd_web, "请输入收货人详细地址");
                return;
            }
            if (this.Request["shdz"].ToString().Length > 40)
            {
                ErrorReturn(wnxd_web, "输入地址字数过长");
                return;
            }

            if (!IsMobilePhone(this.Request["sjhm"]))
            {
                ErrorReturn(wnxd_web, "请输入正确的手机号码");
                return;
            }
            string orderid = this.GenerateOrderId();
            int count;
            if (!int.TryParse(this.Request["count"], out count)) count = 1;
            wnxd_OrderInfo OrderInfo = new wnxd_OrderInfo();
            OrderInfo.Orderid = orderid;
            OrderInfo.UserId = 1100;
            OrderInfo.Username = "Anonymous";
            OrderInfo.ShipTo = Globals.HtmlEncode(this.Request["shr"]);
            OrderInfo.Phone = this.Request["sjhm"];
            OrderInfo.Region = region;
            OrderInfo.Address = this.Request["shdz"] + "  ";
            OrderInfo.Remark = Globals.HtmlEncode(this.Request["guest"]);
            OrderInfo.ShippingModeId = 2;
            OrderInfo.ShipToDate = "时间不限";
            OrderInfo.PaymentTypeId = int.Parse(this.Request["fkfs"]);
            OrderInfo.QQ = "";
            OrderInfo.SubmitDomain = "http://" + this.Request.Url.Host;
            OrderInfo.Source


            int bundlingid;
            string pages = this.Request["page"] == null ? string.Empty : this.Request["page"].ToString();

            string isphone = this.Page.Request["isphone"];
            if (int.TryParse(this.Request["bundlingid"], out bundlingid))
            {
                OrderInfo.isBundling = true;
                OrderInfo.bundlingid = bundlingid;
                OrderInfo.shoppingCart = ShoppingCartProcessor.GetShoppingCart(bundlingid, count);
                if (this.Request["fkfs"] == "2" || this.Request["fkfs"] == "7" || this.Request["fkfs"] == "3")
                {
                    BundlingInfo bundlingInfo = ProductBrowser.GetBundlingInfo(bundlingid);
                    OrderInfo.shoppingCart.ReducedPromotionAmount = bundlingInfo.Price * count * 0.08m;
                    OrderInfo.shoppingCart.IsReduced = true;
                }
            }
            else
            {
                OrderInfo.isSignBuy = true;
                string[] sku = this.Request["product"].Split(',');
                Member user = HiContext.Current.User as Member;
                OrderInfo.shoppingCart = ShoppingCartProcessor.GetShoppingCart_danping(sku[0], count, true);
                for (int i = 1; i < sku.Length; i++)
                {
                    ShoppingCartItemInfo item = new ShoppingCartDao().GetCartItemInfo_danping(user, sku[i], 1);
                    OrderInfo.shoppingCart.LineItems.Add(item);
                }
                if (this.Request["fkfs"] == "2" || this.Request["fkfs"] == "7" || this.Request["fkfs"] == "3")
                {
                    //不同的在线支付减价方式 (wawa1/手机娃娃减价,)
                    switch (pages)
                    {
                        case "wawa1":
                            switch (this.Request.Form["product"].ToString().Split('_')[1])
                            {
                                case "898":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 50 + 49;
                                    break;
                                case "1007":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 200 + 199;
                                    break;
                                case "900":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 150 + 99;
                                    break;
                                case "899":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 100 + 69;
                                    break;
                            }
                            OrderInfo.shoppingCart.IsReduced = true;
                            break;
                        default:
                            OrderInfo.shoppingCart.ReducedPromotionAmount = OrderInfo.shoppingCart.GetTotal() * 0.08m;
                            break;
                    }

                    OrderInfo.shoppingCart.IsReduced = true;
                }
                else
                {
                    switch (pages)
                    {
                        case "wawa1":
                            switch (this.Request.Form["product"].ToString().Split('_')[1])
                            {
                                case "898":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 49;
                                    break;
                                case "1007":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 199;
                                    break;
                                case "900":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 99;
                                    break;
                                case "899":
                                    OrderInfo.shoppingCart.ReducedPromotionAmount = 69;
                                    break;
                            }
                            OrderInfo.shoppingCart.IsReduced = true;
                            break;

                    }

                    //OrderInfo.shoppingCart.IsReduced = true;
                }
            }
            string url = "http://order.x-juse.com/OrderProcess.aspx";
            new Thread(() =>
            {
                json json = new json(OrderInfo);
                WebRequest Request = WebRequest.Create(url);
                Request.Method = "POST";
                Request.ContentType = "application/x-www-form-urlencoded";
                byte[] data = Encoding.UTF8.GetBytes(json.ToString());
                Request.ContentLength = data.Length;
                using (Stream s = Request.GetRequestStream())
                {
                    s.Write(data, 0, data.Length);
                    s.Flush();
                }
                Request.BeginGetResponse(null, null);
                Request.Abort();
            }).Start();
            if (string.IsNullOrEmpty(isphone))
            {
                this.Response.Redirect("/Wait.aspx?orderid=" + orderid, false);
            }
            else
            {
                this.Response.Redirect("/Wait.aspx?orderid=" + orderid + "&isphone=true", false);
            }
        }
        catch (Exception e)
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.AppendLine("客户信息：");
            string ip = "";
            if (HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = HttpContext.Current.Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.AppendLine("连接IP:" + HttpContext.Current.Request.UserHostAddress);
            str.AppendLine("IP:" + ip);
            str.AppendLine("连接主机名:" + HttpContext.Current.Request.UserHostName);
            str.AppendLine("浏览器:" + HttpContext.Current.Request.Browser.Browser);
            str.AppendLine("浏览器版本:" + HttpContext.Current.Request.Browser.MajorVersion.ToString());
            str.AppendLine("操作系统:" + HttpContext.Current.Request.Browser.Platform);
            str.AppendLine("错误信息:");
            str.AppendLine("页面：" + HttpContext.Current.Request.Url.ToString());
            str.AppendLine("错误信息：" + e.Message);
            str.AppendLine("错误源：" + e.Source);
            str.AppendLine("异常方法：" + e.TargetSite);
            str.AppendLine("堆栈信息：" + e.StackTrace);
            str.AppendLine("--------------------------------------------------------------------------------------------------");
            string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            string FileName;
            string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
            if (flist != null && flist.Length > 0)
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                FileInfo fileInfo = new FileInfo(FileName);
                if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                }
            }
            else
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
            }
            File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
        }
    }
    private string GenerateOrderId()
    {
        string str = string.Empty;
        Random random = new Random();
        for (int i = 0; i < 7; i++)
        {
            int num = random.Next();
            str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
        }
        int v = random.Next(0, 9);
        return (DateTime.Now.ToString("yyyyMMdd") + str + v);
    }
</script>
